package com.wisdytech.linkdcs.equipLifeCycle.maintain.service.impl;

import com.wisdytech.linkdcs.equipLifeCycle.maintain.model.MTypeItem;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.model.MaintenancePlan;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.model.MaintenanceType;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.github.pagehelper.PageInfo;
import com.wisdytech.common.bean.Filter;
import com.wisdytech.common.constants.CommonConstants;
import com.wisdytech.common.exception.ServiceException;
import com.wisdytech.common.handler.BaseService;
import com.wisdytech.common.utils.BaseUtil;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.IMTypeItemDao;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.IMaintenancePlanDao;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.dao.IMaintenanceTypeDao;
import com.wisdytech.linkdcs.equipLifeCycle.maintain.service.IMaintenanceTypeService;
import com.wisdytech.linkdcs.partLife.model.Part;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenbin
 * @since 2018-06-09
 */
@Service("iMaintenanceTypeService")
@Transactional
public class MaintenanceTypeServiceImpl extends BaseService<IMaintenanceTypeDao, MaintenanceType> implements IMaintenanceTypeService {

	@Resource
	private IMaintenanceTypeDao iMaintenanceTypeDao;
	@Resource
	private IMTypeItemDao iMTypeItemDao;
	
	@Resource
	private IMaintenancePlanDao iMaintenancePlanDao;
	
	@Override
	public MaintenanceType getTypeById(String pkId) {
		return iMaintenanceTypeDao.selectById(pkId);
	}

	@Override
	public void addType(MaintenanceType maintenanceType, String loginName) {
		EntityWrapper<MaintenanceType> ew = new EntityWrapper<>();
        //验证备件编码的唯一性
        List<MaintenanceType> list = new ArrayList<>();
        list = iMaintenanceTypeDao.selectPage(new Page<Part>(1, 1), ew.eq("TYPE_CODE", maintenanceType.getTypeCode()).eq("del_flag", CommonConstants.DEL_FLAG));
        if (!list.isEmpty()) {
        	throw new ServiceException("该保养类别编码被使用");
        }
        maintenanceType.setPkId(BaseUtil.getUUID());
        maintenanceType.setDelFlag(CommonConstants.DEL_FLAG);
        maintenanceType.setCreateUser(loginName);
        maintenanceType.setCreateDate(new Date());
        int partCount = iMaintenanceTypeDao.insert(maintenanceType);
        if (partCount <= 0) {
            throw new ServiceException("新增失败");
        }		
	}

	@Override
	public PageInfo<MaintenanceType> listTypeAndItemByFilter(String typeCode, String typeName, Filter filter) {
		EntityWrapper<MaintenanceType> ew = new EntityWrapper<>();
        if (StringUtils.isNotBlank(typeCode)) {
        	ew.like("TYPE_CODE", typeCode);
        }
        if (StringUtils.isNotBlank(typeName)) {
        	ew.like("TYPE_NAME", typeName);
        }
		List<MaintenanceType> typeList =super.beforeList(IMaintenanceTypeDao.class, filter).selectList(ew.eq("del_flag", CommonConstants.DEL_FLAG));
		
		if(typeList!=null) {
			for(MaintenanceType type:typeList) {
				List<MaintenanceType> list = iMaintenanceTypeDao.getTypeAndItemName(type.getPkId());
                StringBuilder sb = new StringBuilder();
                for(MaintenanceType maintenanceType : list) {
                    sb.append(maintenanceType.getItemName()).append(";");
                }
                String itemNameReal="";
                if(StringUtils.isNotEmpty(sb.toString())){
                    itemNameReal = sb.toString().substring(0,sb.toString().length()-1);
                }

				type.setItemName(itemNameReal);
			}
		}
		PageInfo<MaintenanceType> page = new PageInfo<>(typeList);
		return page;
	}

	@Override
	public void updateType(MaintenanceType maintenanceType, String loginName) {
		EntityWrapper<MaintenanceType> ew = new EntityWrapper<>();;
        //验证备件编码的唯一性--修改功能
		List<MaintenanceType> list;
		list = iMaintenanceTypeDao.selectPage(new Page<Part>(1, 1),ew.eq("TYPE_CODE", maintenanceType.getTypeCode()).ne("pk_id", maintenanceType.getPkId()));
        if (list.size() > 0){
        	throw new ServiceException("该保养类别编码被使用");
        }
        maintenanceType.setUpdateDate(new Date());
        maintenanceType.setUpdateUser(loginName);
        int operationCount = iMaintenanceTypeDao.updateById(maintenanceType);
        if (operationCount <= 0) {
            throw new ServiceException("修改失败");
        }
		
	}

	@Override
	public void delTypeById(String ids) {
        List<String> idList = new ArrayList<String>();
        String[] id = ids.split(",");
        for (int i = 0; i < id.length; i++) {
            idList.add(id[i]);
        }
        //判断是否被计划引用
        for(String pkId : id) {
        	EntityWrapper<MaintenancePlan> ew = new EntityWrapper<>();
        	ew.eq("TYPE_ID", pkId);
        	 int num = iMaintenancePlanDao.selectCount(ew);
             if (num > 0) {
                 throw new ServiceException("记录中存在被引用的保养类别");
             }
        }
        for(String pkId : id) {
            //删除关联的保养项
            EntityWrapper<MTypeItem> ew = new EntityWrapper<>();
            ew.eq("TYPE_ID", pkId);
            this.iMTypeItemDao.delete(ew);
        }
        int count = iMaintenanceTypeDao.deleteBatchIds(idList);
        if (count <= 0) {
            throw new ServiceException("删除失败");
        }
		
	}

	@Override
	public List<MaintenanceType> listTypeAllBySearch(String search,String modelCode) {
		//加载所有关联了设备的保养类型
		List<MaintenanceType> list = iMaintenanceTypeDao.listTypeAllBySearch(search);
		List<MaintenanceType> realList = new ArrayList<>();
		//通过类别id查询该保养类型是否被计划添加
		for(MaintenanceType type : list) {
			EntityWrapper<MaintenancePlan> ew = new EntityWrapper<>();
			ew.eq("TYPE_ID", type.getPkId()).and().eq("MODEL_CODE", modelCode);
			List<MaintenancePlan> planList = iMaintenancePlanDao.selectList(ew);
			//保存为被计划引用的保养类别
			if(planList.isEmpty()) {
				realList.add(type);
			}
		}

		return realList;
	}

}
